var ajax = require("mlib/io/ajax");
var extend = require("../util/mix");
var wx = require("./jssdk");

module.exports = function(state, options){//
	var that = {};
	if(typeof(options)!="object"){
		options = {};
	}
	var setting = {
		"debug":false,
		"title":"",
		"link":"",
		"imgUrl":"",
		"desc":"",
		"complete":function (res) {},
		"readyfn":function (res) {},//获取签名后并成功加载WeixinJSBridge类对象后执行回调
		"trigger":function (res) {},
		"success":function (res) {},
		"cancel":function (res) {},
		"fail":function (res) {},
	};
	var wxopt = extend(setting,options);
	that.hideshare = function(){
		wx.ready(function(){
			wx.hideMenuItems({
				  menuList: [
					'menuItem:share:appMessage', // 发送给朋友
					'menuItem:share:timeline', // 分享到朋友圈
					'menuItem:share:qq', // 分享到QQ
					'menuItem:share:weiboApp', // 分享到Weibo
					'menuItem:favorite', // 收藏
					'menuItem:share:facebook', // 分享到FB
					'menuItem:share:QZone', // 分享到 QQ 空间
					'menuItem:copyUrl', // 复制链接
					'menuItem:openWithQQBrowser', // 在QQ浏览器中打开
					'menuItem:openWithSafari' // 在Safari中打开
				  ],
				  success: function (res) {
				   // alert('已隐藏“阅读模式”，“分享到朋友圈”，“复制链接”等按钮');
				  },
				  fail: function (res) {
				   // alert(JSON.stringify(res));
				  }
			});
		});
	};
	that.showshare =function(){
		wx.ready(function(){
			// 监听“分享给朋友”
			wx.onMenuShareAppMessage(wxopt);
			// 监听“分享到朋友圈”	
			wx.onMenuShareTimeline(wxopt);		
			// 监听“分享到QQ”
			wx.onMenuShareQQ(wxopt);
			// 监听“分享到微博”
			wx.onMenuShareWeibo(wxopt);
			// 监听“分享到QZone”
			wx.onMenuShareQZone(wxopt);
		});
	};
	that.getsign =function(){
		ajax({
			url: "/index.php?r=jssdk/showsign",
			onSuccess: function (config) {
				  wx.config({
					  debug: wxopt.debug,
					  appId: config.appid,
					  timestamp: config.jstimestamp,
					  nonceStr: config.jsnoncestr,
					  signature: config.signature,
					  jsApiList:["checkJsApi","onMenuShareTimeline","onMenuShareAppMessage","onMenuShareQQ","onMenuShareWeibo","onMenuShareQZone","hideMenuItems","showMenuItems","hideAllNonBaseMenuItem","showAllNonBaseMenuItem","translateVoice","startRecord","stopRecord","onVoiceRecordEnd","playVoice","onVoicePlayEnd","pauseVoice","stopVoice","uploadVoice","downloadVoice","chooseImage","previewImage","uploadImage","downloadImage","getNetworkType","openLocation","getLocation","hideOptionMenu","showOptionMenu","closeWindow","scanQRCode","chooseWXPay","openProductSpecificView","addCard","chooseCard","openCard"]
				  });
				  switch(state){
					  case 'off' :
						  this.hideshare();
						  break;
					  case 'open' :
						  this.showshare();
						  break;
					   case 'ready':
						   wx.ready(function(){
							   wxopt.readyfn(wx);
						   });
						   break;				   
					  
				  }
			}.bind(that),
			onError: function (xmlHttp) {
			},
			onTimeout: function (xmlHttp) {
			}, 
			onAbort: function () {
			} 
		});
	};
	that.init =function(){
		that.getsign();		
	};
//	that.wx = wx;
	return that;
};